package org.jackysoft.service.impl;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Collection;
import java.util.UUID;

import javax.annotation.Resource;
import javax.servlet.http.Part;

import org.jackysoft.data.AbstractDataProvider;
import org.jackysoft.entity.Accessory;
import org.jackysoft.mapper.AttachmentMapper;
import org.jackysoft.service.AttachmentService;
import org.jackysoft.service.OsWorkflowRunnerService;
import org.jackysoft.util.AttTypeManager;
import org.jackysoft.util.FileDownload;
import org.jackysoft.util.IOUtils;
import org.jackysoft.util.StringUtils;
import org.joda.time.DateTime;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Service;

@Service
public class AttachmentServiceImpl extends AbstractDataProvider<Accessory>
		implements AttachmentService {
	
	
	@Resource 
	AttachmentMapper mapper;
	
	
	public AttachmentServiceImpl() {
		
	}

	@Override
	public void remove(Accessory bean, Long refid)
			throws DataAccessException {
	       mapper.removeOfWorkflow(bean.getId(), refid);	

	}

	@Override
	public FileDownload download(String id) throws FileNotFoundException {
		Accessory at = mapper.findOne(id);
		FileDownload di = new FileDownload();
		
		
		
		di.setTitle(StringUtils.toUtf8String(at.getName()));	
		di.setInputStream(new BufferedInputStream(new FileInputStream(new File(at.getPath()))));
		di.setFileType(at.getExt());
		return di;
	}

	@Override
	public void create(Part[] uploads, long workflowId)
			throws DataAccessException, FileNotFoundException, IOException {
		 
		
		for(Part part:uploads){
			Accessory atth = save(part,context.attachmentBase);
			mapper.inert(atth);
		}
		
	
	}	
	
	public Accessory save(Part upload,  String base)
			throws DataAccessException {
		UUID uuid = UUID.randomUUID();
		String ext = StringUtils.splitPostFileName(upload.getSubmittedFileName());
		String relatePath = "attachment" + File.separator + uuid.toString()
				+ "." + ext;
		String urlpath = "attachment/" + uuid.toString() + "." + ext;
		String fname = base + File.separator + relatePath;	
		try {
			IOUtils.copy(upload.getInputStream(), new FileOutputStream(new File(fname)));
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		Accessory ath = new Accessory();
		ath.setId(uuid.toString());
		ath.setUrl(urlpath);
		ath.setPath(fname);
		ath.setCreateDate(DateTime.now().getMillis());
		ath.setName(upload.getSubmittedFileName());
		ath.setExt(ext);
		ath.setType(AttTypeManager.getType(ext));
		return ath;
	}

	@Override
	public Collection<Accessory> findByWorkflow(long workflowId) {
		
		return mapper.findByRefid(workflowId);
	}	

}
